package com.bawei.contentresolver_sms;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Telephony;
import android.util.Log;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    "android.permission.WRITE_SMS",
                    "android.permission.READ_SMS"

            },101);
        }
        query();//查询手机中的短信




    }
    @SuppressLint("Range")
    public void query(){

        getContentResolver().registerContentObserver(Telephony.Sms.CONTENT_URI, true, new ContentObserver(new Handler()) {

            @Override
            public void onChange(boolean selfChange, @Nullable Uri uri) {
                super.onChange(selfChange, uri);
                Cursor c = getContentResolver().query(uri, null, null, null, "_id desc");//
                if (c != null) {
                    if (c.moveToFirst()) {
                        String address = c.getString(c.getColumnIndex("address"));
                        String body = c.getString(c.getColumnIndex("body"));
                        getValidateCode(address,body);//获取短信验证码
                    }
                }


            }
            /**
             * 获取短信验证码
             */
            private void getValidateCode( String address,String body) {

                        Log.d("main", "发件人为:" + address + " ," + "短信内容为:" + body);
                        Pattern pattern = Pattern.compile("(\\d{6})");
                        Matcher matcher = pattern.matcher(body);
                        if (matcher.find()) {
                            String code = matcher.group(0);
                            Log.d("main", "验证码为: " + code);

                        }
                }



        });

    }
}